package com.nio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class MultiplexerTimerServer implements Runnable{
    private Selector selector;
    private ServerSocketChannel channel;
    private volatile  boolean stop;

    public MultiplexerTimerServer(int port){
        try {
            selector = Selector.open();
            channel = ServerSocketChannel.open();
            channel.configureBlocking(false);
            channel.socket().bind(new InetSocketAddress(port),1024);
            channel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("TimeServer is start, port:" + port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @Override
    public void run() {
        try {
            selector.select();
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> ketIt = keys.iterator();
            SelectionKey key = null;

            while (ketIt.hasNext()){
                key = ketIt.next();
                ketIt.remove();
                handler(key);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void handler(SelectionKey key){

    }
}
